import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_xxyk/constant/api.dart';
import 'package:flutter_xxyk/model/column_lesson.dart';
import 'package:flutter_xxyk/model/product_detail.dart';
import 'package:flutter_xxyk/pages/products/widgets/detail_nav_bar.dart';
import 'package:flutter_xxyk/widgets/lesson.dart';
import 'package:get_it/get_it.dart';

class ColumnDetailPage extends StatefulWidget {
  const ColumnDetailPage({Key? key}) : super(key: key);

  @override
  _ColumnDetailPageState createState() => _ColumnDetailPageState();
}

class _ColumnDetailPageState extends State<ColumnDetailPage> with SingleTickerProviderStateMixin {
  final Dio dio = GetIt.I<Dio>();

  bool _isLoading = true;

  bool _isLessonLoading = true;

  late TabController _tabController;

  ProductDetail? productDetail;

  int lessonTotal = 0;

  List<ColumnLesson> lessonList = [];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      getDetail();
      getLessons();
    });
  }

  Future<void> getDetail() async {
    final pid = ModalRoute.of(context)!.settings.arguments as String;
    _isLoading = true;
    final res = await dio.get("/h5/mine/column/detail/${pid}", queryParameters: {
      "shop_id": ApiConstant.SHOP_ID,
    });
    final json = res.data["data"];
    setState(() {
      productDetail = ProductDetail.fromJson(json);
      _isLoading = false;
    });
  }

  Future<void> getLessons() async {
    final pid = ModalRoute.of(context)!.settings.arguments as String;
    _isLessonLoading = true;
    final res = await dio.get("/h5/mine/column/page_column_lessons", queryParameters: {
      "shop_id": ApiConstant.SHOP_ID,
      "columnId": pid,
      "isDesc": false,
    });
    final json = res.data["data"];
    setState(() {
      lessonTotal = json['total'];
      lessonList = (json['records'] as List).map((r) => ColumnLesson.fromJson(r)).toList();
      _isLessonLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _isLoading
          ? Center(
              child: SpinKitPulse(
                color: Theme.of(context).colorScheme.secondary,
                size: 50.0,
              ),
            )
          : NestedScrollView(
              headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
                return [
                  SliverAppBar(
                    backgroundColor: Colors.white,
                    toolbarHeight: 0,
                    bottom: PreferredSize(
                      preferredSize: Size.fromHeight(71),
                      child: CustomAppBar(),
                    ),
                  ),
                  SliverAppBar(
                    backgroundColor: Colors.white,
                    pinned: true,
                    expandedHeight: 360,
                    collapsedHeight: 56,
                    flexibleSpace: FlexibleSpaceBar(
                      collapseMode: CollapseMode.pin,
                      background: _buildBase(),
                    ),
                    toolbarHeight: 0,
                    bottom: PreferredSize(
                      preferredSize: Size.fromHeight(0),
                      child: _buildTabBar(),
                    ),
                  ),
                ];
              },
              body: _buildInfoPanel(),
            ),
    );
  }

  Widget _buildBase() {
    return Card(
      child: Column(
        children: [
          Image.network(productDetail!.imgUrl!),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
            child: Column(
              children: [
                Row(
                  children: <Widget>[
                    Container(
                      color: Color(0xffe5f1ff),
                      padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                      child: Text(
                        "专栏",
                        style: TextStyle(color: Color(0xff007aff)),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 20),
                      child: Text(
                        "${productDetail!.title!}",
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 18,
                          color: Color(0xff333333),
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    )
                  ],
                ),
                Container(
                  width: double.infinity,
                  padding: EdgeInsets.only(top: 15, bottom: 10),
                  child: DefaultTextStyle(
                    style: TextStyle(
                      color: Color(0xff9d9fa7),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text.rich(
                          TextSpan(children: [
                            WidgetSpan(
                              child: Padding(
                                padding: EdgeInsets.only(
                                  right: 10,
                                ),
                                child: Icon(
                                  Icons.access_time_outlined,
                                  color: Color(0xff9d9fa7),
                                  size: 18,
                                ),
                              ),
                              alignment: PlaceholderAlignment.middle,
                            ),
                            TextSpan(text: "${productDetail!.resourceCnt!}课时·更新于${productDetail!.publishTime!}"),
                          ]),
                          textAlign: TextAlign.start,
                        ),
                        Divider(),
                        Text(
                          "${productDetail!.summary}",
                          style: TextStyle(fontSize: 16),
                        )
                      ],
                    ),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _buildTabBar() {
    return TabBar(
        controller: _tabController,
        labelColor: Colors.black,
        labelStyle: TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.bold,
        ),
        unselectedLabelStyle: TextStyle(
          fontWeight: FontWeight.normal,
        ),
        indicatorPadding: EdgeInsets.symmetric(horizontal: 82),
        indicatorWeight: 3,
        tabs: [
          Tab(
            text: "详情",
          ),
          Tab(
            text: "目录",
          ),
        ]);
  }

  Widget _buildInfoPanel() {
    return Center(
      child: TabBarView(
        controller: _tabController,
        children: [
          _buildInfoTab(),
          _buildCatalogTab(),
        ],
      ),
    );
  }

  Widget _buildInfoTab() {
    Widget html = Html(
      data: productDetail!.descrb!,
      style: {
        "*": Style(
          lineHeight: LineHeight.number(1.42),
          margin: EdgeInsets.zero,
        ),
      },
    );
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10),
      child: html,
    );
  }

  Widget _buildCatalogTab() {
    return _isLessonLoading
        ? Center(
            child: SpinKitPulse(
              color: Theme.of(context).colorScheme.secondary,
              size: 50.0,
            ),
          )
        : ListView.separated(
            padding: EdgeInsets.symmetric(horizontal: 15, vertical: 12),
            itemCount: lessonList.length,
            separatorBuilder: (BuildContext context, int index) {
              return SizedBox(
                height: 20,
              );
            },
            itemBuilder: (context, index) {
              final lesson = lessonList[index];
              return Ink(
                color: Colors.white,
                child: InkWell(
                  onTap: () {},
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      LessonPic(
                        imgUrl: lesson.imgUrl!,
                        imgHeight: 90,
                        type: lesson.type,
                      ),
                      Expanded(
                        child: Container(
                          padding: EdgeInsets.only(left: 10),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              SizedBox(
                                height: 5,
                              ),
                              Text(
                                "${lesson.title}",
                                textAlign: TextAlign.left,
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 15,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              Text(
                                "${lesson.summary}",
                                style: TextStyle(
                                  fontSize: 13,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              )
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              );
            },
          );
  }
}
